package com.bacon.gmall.product.utils;

import com.alibaba.nacos.common.util.ClassUtils;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * @author： bacon、
 * @version： 1.0
 * @create： 2020-12-21 18:15
 * @description:
 */
public class FileUploadUtil {

    /**
     *
     * @param filename fdfs_client.conf所配置的东西
     * @param file
     * @return
     */
    public static String fileUpload(String filename, MultipartFile file) {

        String path = ClassUtils.getDefaultClassLoader().
                getResource("fdfs_client.conf").getPath();

        try {
            ClientGlobal.init(path);
            TrackerClient trackerClient = new TrackerClient();
            //连接Tracker
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = null;

            //连接上存储节点
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);

            String ext = FilenameUtils.getExtension(file.getOriginalFilename());

            //上传图片
            String p = storageClient1.upload_appender_file1(file.getBytes(), ext, null);

            return p;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }

        return null;
    }
}